package com.happy3w.task.composer;

import com.happy3w.toolkits.sort.DependSorter;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Getter
@AllArgsConstructor
@EqualsAndHashCode
public class DependItem {
    public static final String CSV_HEAD = "from,to,weight";

    private final String from;
    private final String to;

    public String formatGraphItem() {
        return from + "," + to + ",1";
    }

    @Override
    public String toString() {
        return from + "->" + to;
    }

    public static List<DependItem> sort(List<DependItem> items) {
        Map<String, Set<String>> holders = new HashMap<>();
        for (DependItem item : items) {
            holders.computeIfAbsent(item.getFrom(), $ -> new HashSet<>())
                    .add(item.getTo());
        }

        List<String> sortedItems = DependSorter.sort(holders.keySet(), holders::get, k -> new HashSet<>(Arrays.asList(k)));
        return sortedItems.stream()
                .flatMap(from -> holders.get(from).stream()
                        .map(to -> new DependItem(from, to)))
                .collect(Collectors.toList());
    }
}
